package com.bwc.codevideo

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class TrainingActivity : AppCompatActivity() {
    private var et_running_height : EditText?= null
    private var et_running_weight : EditText?= null
    private var et_running_age : EditText?= null
    private var et_running_gender : EditText?= null
    private var et_running_health : EditText?= null
    private var et_running_target : EditText?= null
    private var et_running_tupo : EditText?= null
    private var et_running_time : EditText?= null
    private var et_running_nandu : EditText?= null

    private var btn_send_output : Button?= null
    private var tv_xiaohaotianshu : TextView?= null

    private var trainingProfile: TrainingProfile? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_training)
        et_running_height = findViewById(R.id.et_running_height)
        et_running_weight = findViewById(R.id.et_running_weight)
        et_running_age = findViewById(R.id.et_running_age)
        et_running_gender = findViewById(R.id.et_running_gender)
        et_running_health = findViewById(R.id.et_running_health)
        et_running_target = findViewById(R.id.et_running_target)
        et_running_tupo = findViewById(R.id.et_running_tupo)
        et_running_time = findViewById(R.id.et_running_time)
        et_running_nandu = findViewById(R.id.et_running_nandu)
        btn_send_output = findViewById(R.id.btn_send_output)
        tv_xiaohaotianshu = findViewById(R.id.tv_xiaohaotianshu)

        sendAi()
    }

    private fun sendAi() {
        btn_send_output?.setOnClickListener {
            if (true){

                val logging = HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }

                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .build()

                val retrofit = Retrofit.Builder()
                    .baseUrl("https://api.coze.cn/v1/")
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

                val cozeApi = retrofit.create(CozeApi::class.java)
                val age = et_running_age?.text.toString().toInt()
                val gender = et_running_gender?.text.toString()
                val height = et_running_height?.text.toString().toInt()
                val weight = et_running_weight?.text.toString().toInt()
                val healthConditions = et_running_health?.text.toString()

                val primaryGoal = et_running_target?.text.toString()
                val eventTarget = et_running_tupo?.text.toString()

                val availableTime = et_running_time?.text.toString().toInt()

                val trainingStyle = et_running_nandu?.text.toString()

                // 创建新的 TrainingProfile 对象
                trainingProfile = TrainingProfile(
                    basic_info = BasicInfo(age, gender, height, weight, healthConditions),
                    training_goal = TrainingGoal(primaryGoal, eventTarget),
                    training_schedule = TrainingSchedule(availableTime),
                    preferences = Preferences( training_style = trainingStyle)
                )
                val gson = Gson()
                val mapType = object : TypeToken<Map<String, Any>>() {}.type
                val parameters: Map<String, Any> = gson.fromJson(gson.toJson(trainingProfile), mapType)
                val request = CozeRequest(
                    workflowId = "7522419437992247331",
                    parameters = parameters
                )
                val call = cozeApi.runWorkflow(request, "Bearer pat_JG7C6fIyVcpyDjgnyo9w29Y8YX3a1NXX9Rc7lHffka1mSkeowPbk48jvGRJOSS2r")
                call.enqueue(object : Callback<ResponseBody> {
                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        if (response.isSuccessful) {
                            val responseBody = response.body()?.string()
                            val apiResponse = Gson().fromJson(responseBody, ApiResponse::class.java)

                            val data = Gson().fromJson(apiResponse.data, RunningData::class.java)
                            tv_xiaohaotianshu?.text = "请求的结果显示在这里：${data.running_calorie},${data.running_day}"

                            trainingProfile = TrainingProfile(
                                basic_info = BasicInfo(age, gender, height, weight, healthConditions),
                                training_goal = TrainingGoal(primaryGoal, eventTarget),
                                training_schedule = TrainingSchedule(availableTime),
                                preferences = Preferences( training_style = trainingStyle),
                                running_sport = RunningData(data.running_calorie,data.running_day)
                            )
                            sendSportxiangqing(trainingProfile!!)
                            Log.d("TrainingActivity---", "成功: $responseBody")
                        } else {
                            Log.e("TrainingActivity---", "错误码: ${response.code()}")
                        }
                    }

                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Log.e("TrainingActivity---", "网络失败: ${t.message}")
                    }
                })

            }else{
                Toast.makeText(this,"当前数据不能为空", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun sendSportxiangqing(trainingProfiles: TrainingProfile) {
        Log.d("TrainingActivity---", "sendSportxiangqing: $trainingProfiles")
        val gson = Gson()
        val mapType = object : TypeToken<Map<String, Any>>() {}.type
        val parameters: Map<String, Any> = gson.fromJson(gson.toJson(trainingProfiles), mapType)
        val request = CozeRequest(
            workflowId = "7522736589316636724",
            parameters = parameters
        )
        val logging = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }

        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)  // 设置连接超时
            .readTimeout(20, TimeUnit.SECONDS)     // 设置读取超时
            .writeTimeout(20, TimeUnit.SECONDS)    // 设置写入超时
            .addInterceptor(logging)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl("https://api.coze.cn/v1/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val cozeApi = retrofit.create(CozeApi::class.java)
        val call = cozeApi.runWorkflow(request, "Bearer pat_TYUcxqCZwiNP5dH0YuhBkXnFRA7JeXRizJLjLPDpwprmgo99cucvOmKLbKMIHpxF")
        call.enqueue(object : Callback<ResponseBody> {
            @SuppressLint("SuspiciousIndentation")
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.isSuccessful) {
                    val responseBody = response.body()?.string()
                    val apiResponse = Gson().fromJson(responseBody, ApiResponse::class.java)

                    val data = Gson().fromJson(apiResponse.data, TitleData::class.java)
//                            val responseJson = JSONObject(responseBody) // 第一步解析外层 JSON
//                            val nestedData = responseJson.getString("data") // 这是嵌套的 JSON 字符串
//                            val innerJson = JSONObject(nestedData) // 第二步解析内层 JSON
//                            val result = innerJson.getString("data") // 最终拿到你要的内容
//                            Log.d("TrainingActivity---", result)
//                    tv_xiaohaotianshu?.text = "请求的结果显示在这里：${data.kaluli},${data.output}"

                    tv_xiaohaotianshu?.text = data.title?.get(0)
//                    trainingProfile = TrainingProfile(title = TitleData(data))
                        Log.d("TrainingActivity---", "onResponse: $data,${data.title},${data.title?.size}")
                    Log.d("TrainingActivity---", "成功: $responseBody")
                } else {
                    Log.e("TrainingActivity---", "错误码: ${response.code()}")
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Log.e("TrainingActivity---", "网络失败: ${t.message}")
            }
        })

    }
}



data class ApiResponse(
    val code: Int,
    val cost: String,
    val data: String,   // data 字段是字符串
    val debug_url: String,
    val msg: String,
    val token: Int
)
